import pandas as pd
import json
import re

def dms_to_decimal(dms_str):
    """将度分秒格式(如128°31′15″)转换为十进制"""
    # 使用正则表达式提取度、分、秒数值
    match = re.match(r'(\d+)°(\d+)′(\d+)″', dms_str)
    if not match:
        return 0.0

    degrees = float(match.group(1))
    minutes = float(match.group(2))
    seconds = float(match.group(3))

    return degrees + minutes / 60 + seconds / 3600

def excel_to_geojson(excel_path, geojson_path):
    # 读取Excel文件
    df = pd.read_excel(excel_path)

    # 构建GeoJSON结构
    geojson = {
        "type": "FeatureCollection",
        "name": "瞭望塔",
        "crs": {
            "type": "name",
            "properties": {
                "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
            }
        },
        "features": []
    }

    # 遍历数据行，构建每个要素
    for _, row in df.iterrows():
        # 转换经纬度为十进制
        longitude = dms_to_decimal(row['东经'])
        latitude = dms_to_decimal(row['北纬'])

        # 创建要素
        feature = {
            "type": "Feature",
            "properties": {
                "塔名": row['塔名']
            },
            "geometry": {
                "type": "Point",
                "coordinates": [longitude, latitude]
            }
        }

        geojson['features'].append(feature)

    # 写入GeoJSON文件
    with open(geojson_path, 'w', encoding='utf-8') as f:
        json.dump(geojson, f, ensure_ascii=False, indent=2)

    print(f"成功生成GeoJSON文件: {geojson_path}")
    print(f"共包含 {len(geojson['features'])} 个瞭望塔点位")

if __name__ == "__main__":
    # 输入Excel文件路径和输出GeoJSON文件路径
    excel_file = r"C:\Users\ma\Desktop\瞭望塔.xlsx"  # 替换为你的Excel文件路径
    geojson_file = r"C:\Users\ma\Desktop\鹤北geojson\瞭望塔.geojson"  # 输出的GeoJSON文件路径


    # 转换并生成文件
    excel_to_geojson(excel_file, geojson_file)
